let socket;
export const connectUeMsg = (onopen, onmessage, onerror) => {
  socket = new WebSocket(`/pixelstream_ws/appMsg`);

  socket.addEventListener("open", function (event) {
    // console.log("Connected to WS Server", event);
    // 如果需要，可以发送初始状态到服务器
    socket.send("Client connected");
    // console.log("Client connected", socket);
    onopen(event);
  });

  socket.addEventListener("message", function (event) {
    // console.log("Message from server ", event);
    onmessage(event);
    // handleMsg(event.data);
  });

  // 处理 WebSocket 错误
  socket.addEventListener("error", function (event) {
    // console.log("WebSocket error: ", event);
    onerror(event);
  });
};

export const disconnectUeMsg = () => {
  // 组件卸载之前，关闭 WebSocket 连接
  if (socket) {
    // console.log("socket", socket);
    socket.close();
    socket = null;
    // console.log("socket close", socket);
  }
};
